
import "./index.scss"
import { Form, Input, Tabs, TabPanel, Button, Toast } from "tdesign-mobile-react";
import logo from "../../assets/images/image_entry.png";
import { useState, useMemo, useEffect, useRef } from "react";
import { User1Icon, UserLockedIcon, MobileIcon, CodeIcon } from "tdesign-icons-react"
import utils from "../../utils/utils";
import Cookies from "js-cookie";

const FormItem = Form.FormItem;

function Login() {
    let isTell = true;
    const isInit = useRef(false);
    const rules = useMemo(() => ({
        tellphone: [{
            len: 11,
            message: "手机号格式错误"
        }, {
            validator: (val) => {
                let tags = false;
                utils.REG.phone(val, (e) => {
                    if (e.code === 200) {
                        tags = true;
                    }
                });
                return tags;
            }, message: "请输入正确的手机号"
        }, {
            whitespace: true,
            message: "手机号不能为空"
        }],
        code: [{
            whitespace: true,
            message: "验证码不能为空"
        }, {
            len: 6,
            message: "必须为6位数字"
        }]
    }), []);
    const iconSize = 26;
    const [isWait, setIsWait] = useState(false);
    const [data, setData] = useState({
        username: "",
        password: ""
    });
    const refForm = useRef(null);
    const refTellForm = useRef(null);
    const [tell, setTell] = useState({
        tellphone: "15985070989",
        code: "",
        wait: false,
        time: (60 * 60)
    });
    const [codeImage] = useState(utils.API.APP_IMG_CODE);
    const refCodeImage = useRef(null);
    useEffect(() => {
        if (isInit.current) {
            return;
        }
        if (refTellForm.current && rules) {
            refTellForm.current.setValidateMessage(rules);
        }
        if (refForm.current && rules) {
            refForm.current.setValidateMessage(rules);
        }
        isInit.current = true;
    }, [rules])
    useEffect(() => {
        if (tell.wait) {
            Toast({
                message: "发送请求成功", theme: "success"
            })
        }
    }, [tell.wait]);

    // 登录
    function login() {
        setIsWait(true);
        if (isTell) { // 手机号登录
            const { tellphone, code } = { ...tell },
                data = { tellphone, code };
            utils.NET.post("/login", {
                data
            }).then(res => {
                if (!res) {
                    showToast("服务器错误", "error");
                    return;
                } else {
                    switch (res.code) {
                        case 1:
                            showToast(res.msg, "success");
                            if (res.token) {
                                Cookies.set("token", res.token, {
                                    expires: 30
                                });
                            }
                            setTimeout(() => {
                                window.location.reload();
                            }, 800);
                            break;
                        case 2:
                            showToast(res.msg, "error");
                            break;
                        case 3:
                            showToast(res.msg, "error");
                            break;
                        case 4:
                            showToast("禁止登录：" + res.msg, "error");
                            break;
                    }
                    if (res.code != 1 && res.code !== 4) {
                        resetCode();
                    }
                }
            }).catch(err => {
                console.error("eror", err);
            }).finally(() => {
                setIsWait(false);
            });
        } else {
            
            // 账号登录
        }
    }
    // 显示提示
    function showToast(message, type = "info") {
        Toast[type]({
            message,
            preventScrollThrough: true,
            showOverlay: true
        })
    }
    // 提交验证表单
    function loginSubmit(e) {
        if (e.validateResult) {
            login();
            showToast("正在登录", "loading");
        } else {
            showToast("请正确填写信息", "warning");
        }
    }
    function sendRequest() { // 发送请求头
        utils.NET.post("/media");
    }
    sendRequest();
    function resetCode() {
        let dom = refCodeImage.current;
        if (dom) {
            let img = document.querySelector("." + dom.className + " img");
            if (img) {
                img.src = logo;
                img.onload = function () {
                    this.src = utils.API.APP_IMG_CODE;
                    this.onload = () => void (0)
                }
            }
        }
    }
    return (<>
        <div className="login-container">
            <div className="main-content">
                <Tabs animation={{
                    duration: 100,
                    lazy: true
                }} swipeable={false} size="large" defaultValue={"tab-tell"} onChange={(e) => isTell = e === "tab-tell" ? true : false} theme="card">
                    <TabPanel disabled={isWait} label="手机号登录" value="tab-tell">
                        <Form
                            ref={refTellForm}
                            disabled={isWait}
                            rules={rules}
                            showErrorMessage
                            labelWidth={iconSize + 8}
                            labelAlign="right"
                            onSubmit={loginSubmit}
                            preventSubmitDefault={true}
                        >
                            <FormItem name="tellphone" label={
                                <MobileIcon size={iconSize} />
                            } >
                                <Input type="tel" maxlength={11} borderless value={tell['tellphone']} defaultValue='15985070989' onChange={e => {
                                    let val = utils.STR.remove_blank(e);
                                    tell.tellphone = val;
                                    setTell({ ...tell });
                                }} placeholder="请输入手机号"></Input>
                            </FormItem>

                            <FormItem name="code" label={<CodeIcon size={iconSize} />} >
                                <Input defaultValue='' type="text" maxlength={6} borderless value={tell.code} placeholder="请输入6位数验证码" onChange={(e) => {
                                    let val = utils.STR.remove_blank(e);
                                    tell.code = val;
                                    setTell({ ...tell });
                                }} suffix={
                                    <div className="code-container" ref={refCodeImage} onClick={resetCode}>
                                        <img className="image-code" src={codeImage} />
                                    </div>
                                }></Input>
                            </FormItem>
                            <div className="form-button-group">
                                <Button theme="primary" type="submit" disabled={isWait} block size="large">登录</Button>
                            </div>
                        </Form>
                    </TabPanel>
                    <TabPanel disabled={isWait} label="帐号登录" value="tab-acc">
                        <Form ref={refForm} disabled={isWait} preventSubmitDefault={true} labelWidth={iconSize + 8} labelAlign="right">
                            <FormItem label={
                                <User1Icon size={iconSize} />
                            } >
                                <Input defaultValue='' borderless value={data.username} onChange={(e) => {
                                    let val = utils.STR.remove_blank(e);
                                    data.username = val;
                                    setData({ ...data });
                                }} placeholder="请输入用户名"></Input>
                            </FormItem>
                            <FormItem label={<UserLockedIcon size={iconSize} />} >
                                <Input defaultValue='' onChange={(e) => {
                                    let val = utils.STR.remove_blank(e);
                                    data.password = val;
                                    setData({ ...data });
                                }} borderless value={data.password} type="password" placeholder="请输入密码"></Input>
                            </FormItem>
                            <div className="form-button-group">
                                <Button theme="primary" disabled={isWait} block size="large" loading={isWait} onClick={login}>登录</Button>
                            </div>
                        </Form>
                    </TabPanel>
                </Tabs>
            </div>
        </div>
    </>)
}

export default Login